<?php
namespace app\api\controller;
use app\wechat\service\JwtService;
use Decimal\Decimal;
use think\admin\Controller;
use think\Request;
use think\facade\Db;
use think\Validate;
use EasyWeChat\Factory;

/**
 * 前端管理
 */
class Index extends Controller
{
    //明一宏业商户号
    private $myhy_options = [
        'app_id'  => 'wx504958290f5566b7',
        'secret'  => '145dc6351dde0a2ae610e8713a01e9a0',     // AppSecret
        'aes_key' => 'D0C1EAA33E71636574416DB12104F0EC',     // EncodingAESKey，安全模式与兼容模式下请一定要填写！！！
        'mch_id'  =>'1700134471',
        'key'     => 'D0C1EAA33E71636574416DB12104F0EC'
    ];
    /** 微信登录方法 */
    public function wxlogin()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $uniacid=input("uniacid",1);
            $app=Db::name("sassapply")->where("id",$uniacid)->find();
            $js_code = $data["code"];
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$app["appid"]."&secret=".$app["secret"]."&js_code={$js_code}&grant_type=authorization_code";
            
            $ret = $this->makeRequest($url);
            if ($ret["code"] == 200) {
                $result = json_decode($ret["result"], true);
                if ($result) {
                    $sess=$result["session_key"];
                    $aa=Db::name('wechat_userinfo')->where("openid",$result['openid'])->where("uniacid",$uniacid)->find();
                    if($aa){
                        $result["integral"]=$aa["integral"];
                        $result["user_id"]=$aa["id"];
                        $result["jxs_integral"]=$aa["jxs_integral"];
                        Db::name('wechat_userinfo')->where(['openid'=>$result['openid']])->update(['session_key'=>$sess]);
                    }else{
                        $add["session_key"]=$sess;
                        $add["openid"]=$result['openid'];
                        $add["uniacid"]=$uniacid;
                        $add["create_time"]=date("Y-m-d H:i:s");
                        $result["integral"]=0;
                        $user_id=Db::name('wechat_userinfo')->insertGetId($add);
                        $result["user_id"]=$user_id;
                        $result["jxs_integral"]=0;
                    }
                    
                    return xcx_success($result);
                }
            } else {
				file_put_contents("wxlogin_error.log",date("Y-m-d H:i:s")."=>".json_encode($ret,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                return "";
            }
        }
    }
    
    public function get_user_info(){
        $unionid = input('unionid');
        $openid = input('openid');
        $wxuserinfo = input('wxuserinfo');
        $validate = new Validate([
            'openid'=>'require'
        ],[
            'openid.require'=>'openid不能为空'
        ]);
        $validate_res = $validate->check(['openid'=>$openid]);
        if (!$validate_res){
            return xcx_error($validate->getError());
        }else{
            $userinfo = Db::name('wechat_userinfo')->where('openid',$openid)->field('nickname,integral,headimgurl,rec_mobile,realname,baby_birthday,baby_sex,jxs_integral')->find();
            return xcx_success($userinfo);
        }
    }
    
    /** 获取微信授权手机号 */
    public function get_user_phone()
    {
        
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $session_key = $data["session_key"];
            $user_id=($data["user_id"])?$data["user_id"]:0;
            $openid=$data["openid"];
            $ret = decryptData($data["encryptedData"], $data["iv"],$session_key,MMB_WX_APPID);
            if(isset($ret["code"])){
                file_put_contents("guiqing.txt",json_encode($ret).PHP_EOL,FILE_APPEND);
                if($ret["code"] < 0){
                    $json=info(true);
                    $json["data"]="41003";
                    return json_encode($json);
                }   
                $retdata=json_decode($ret["data"],true);
                $mobile=$retdata["phoneNumber"];
                $json=info(true);
                $json["data"]=$retdata;
                return json_encode($json);
            }else{
                $json=info(false);
                $json["info"]=$ret["msg"];
                return json_encode($json);
            }
        }
    }
    
     //小程序授权手机号解密
    public function  decrypt_phone(){
        //获取参数
        $params = input();
        $options = [
            'mini_program' => [
                'app_id'   => 'wxe4bade0c78330859',
                'secret'   => 'acdb704d3fa411a2c754481d13f7ad68',
                'aes_key'  => 'wissun666wissun321wissun123wissu'
            ]
        ];
        $app = Factory::mini_program($this->myhy_options);
        $obj =$app->auth->session($params['code']);
        $res = $app->encryptor->decryptData($obj["session_key"], $params['iv'], $params['encryptedData']);
        
        $mobile = $res['phoneNumber'];
        if($params['user_id']){
            Db::name('wechat_userinfo')->where(['id'=>$params['user_id']])->update(['rec_mobile'=>$mobile]);
        }
        $telStrlen = mb_strlen($mobile,'utf-8');
        $telThree = mb_substr($mobile,0,3);
        $telTwo = mb_substr($mobile,-2,2);
        $mobile =  $telThree . str_repeat("*",$telStrlen - 5) . $telTwo;
        return xcx_success(['mobile'=>$mobile,'mobile2'=>$res['phoneNumber']]);
    }
    
    /** 模拟浏览器访问 */
    function makeRequest($url, $params = array(), $expire = 0, $extend = array(), $hostIp = '')
    {
        if (empty($url)) {
            return array('code' => '100');
        }
        $_curl = curl_init();
        $_header = array(
            'Accept-Language: zh-CN',
            'Connection: Keep-Alive',
            'Cache-Control: no-cache'
        );
        // 方便直接访问要设置host的地址
        if (!empty($hostIp)) {
            $urlInfo = parse_url($url);
            if (empty($urlInfo['host'])) {
                $urlInfo['host'] = substr(DOMAIN, 7, -1);
                $url = "http://{$hostIp}{$url}";
            } else {
                $url = str_replace($urlInfo['host'], $hostIp, $url);
            }
            $_header[] = "Host: {$urlInfo['host']}";
        }
        // 只要第二个参数传了值之后，就是POST的
        if (!empty($params)) {
            curl_setopt($_curl, CURLOPT_POSTFIELDS, http_build_query($params));
            curl_setopt($_curl, CURLOPT_POST, true);
        }
        if (substr($url, 0, 8) == 'https://') {
            curl_setopt($_curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($_curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($_curl, CURLOPT_URL, $url);
        curl_setopt($_curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($_curl, CURLOPT_USERAGENT, 'API PHP CURL');
        curl_setopt($_curl, CURLOPT_HTTPHEADER, $_header);
        if ($expire > 0) {
            curl_setopt($_curl, CURLOPT_TIMEOUT, $expire); // 处理超时时间
            curl_setopt($_curl, CURLOPT_CONNECTTIMEOUT, $expire); // 建立连接超时时间
        }
        // 额外的配置
        if (!empty($extend)) {
            curl_setopt_array($_curl, $extend);
        }
        $result['result'] = curl_exec($_curl);
        $result['code'] = curl_getinfo($_curl, CURLINFO_HTTP_CODE);
        $result['info'] = curl_getinfo($_curl);
        if ($result['result'] === false) {
            $result['result'] = curl_error($_curl);
            $result['code'] = -curl_errno($_curl);
        }
        curl_close($_curl);
        return $result;
    }
    
     //更新用户基本信息
    public function update_basic_info(){
        $user_id = input('user_id');
        $headimgurl = input('headimgurl');
        $nickname = input('nickname');
        if(empty($headimgurl)){
            $headimgurl="https://ayh.wissun.net/static/newhome/img/nologo.png";
        }
        Db::name('wechat_userinfo')->where('id',$user_id)->update([
            'headimgurl'=>$headimgurl,
            'nickname'=>$nickname
            ]);
        return xcx_success(['msg'=>'更新成功']);
    }
    
    //更新用户基本信息
    public function update_basic_info2(){
        $user_id = input('user_id');
        $headimgurl = input('headimgurl');
        $nickname = input('nickname');
        if(empty($headimgurl)){
            $headimgurl="https://ayh.wissun.net/static/newhome/img/nologo.png";
        }
        Db::name('wechat_userinfo')->where('id',$user_id)->update([
            'rec_mobile'=>input("rec_mobile"),
            "realname"=>input("realname"),
            "baby_sex"=>input("baby_sex"),
            "baby_birthday"=>input("baby_birthday"),
        ]);
        return xcx_success(['msg'=>'更新成功']);
    }
    
    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     * @return int 成功0，失败返回对应的错误码
     */
    function decryptData($encryptedData, $iv,$session_key,$APPID="")
    {
        if (strlen($session_key) != 24) {
            return array("code" => -41001, "msg" => "encodingAesKey 非法");
        }
        $aesKey = base64_decode($session_key);
        if (strlen($iv) != 24) {
            return array("code" => -41002, "msg" => "");
        }
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj = json_decode($result);
    
        if ($dataObj == NULL) {
            return array("code" => -41003, "msg" => "aes 解密失败");
        }
        if($APPID){
            if ($dataObj->watermark->appid != $APPID) {
                $data["msg"] = -41003;
                $data["msg"] = "aes 解密失败";
                return $data;
            }
        }
        return array("code" => 0, "data" => $result);
    }
}